package demo.issuetracker.dao.jpa;

import demo.issuetracker.entity.UploadedFile;
import demo.issuetracker.entity.User;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.CascadeType;

import org.apache.commons.codec.binary.Base64;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * User
 */
@Entity
@Table(name="user")
public class JpaUser implements User {
    private static final long serialVersionUID = 1L;



    /** The username of the user */
    @Id
    @Basic
    private String username;

    /** 
     * Get Username.
     *  
     * @return the username
     */
    public String getUsername() {
       return this.username;
    }

    /**
     * Set Username
     *
     * @param username
     */
    public void setUsername(String username) {
        this.username = username;
    }



    /** The password of the user */
    @Basic
    private String password;

    /** 
     * Get Password.
     *  
     * @return the password
     */
    public String getPassword() {
       return this.password;
    }

    /**
     * Set Password
     *
     * @param password
     */
    public void setPassword(String password) {
        this.password = encrypt(password);
    }


    public static synchronized String encrypt(String plaintext) {
        if (plaintext == null) {
            return null;
        }
    
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("System is not ready.", e);
        }
        try {
            md.update(plaintext.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("System is not ready.", e);
        }

        byte raw[] = md.digest(); // step 4
        // Don't modify the charset, or old passwords won't match anymore
        return new String((new Base64().encode(raw)), Charset.forName("US-ASCII"));
    }

    public String primaryKey() {
        return getUsername();
    }
    
    @Override
    public String toString() {
        return primaryKey();
    }
}// clickframes::version=2440618566::clickframes